﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WebApi000.Domain;
using WebApi000.Interface;

namespace WebApi000.implementation
{
    public class EfRespository<T> : IRespository<T> where T : BaseEntity
    {

        private readonly Admin5200DbContext db;

        private DbSet<T> _entity;

        protected DbSet<T> Entity 
        { get
            {
                if (_entity == null)
                {
                    _entity = db.Set<T>();
                }
                return _entity;
            }
        }

        public IQueryable<T> Table
        {
            get
            {
                return Entity;
            }
        }

        public EfRespository(Admin5200DbContext dbContext)
        {
            db = dbContext;
        }
        public void Delete(T entity)
        {
            this._entity.Remove(entity);

            db.SaveChanges();
        }

        public void Delete(int id)
        {
            var row = Table.Where(x => x.Id == id ).FirstOrDefault();
            Delete(row);
            db.SaveChanges();
        }

        

        public T GetById(int id)
        {
            return _entity.Where(x => x.Id == id).SingleOrDefault();
        }

        public void Insert(T entity)
        {
            _entity.Add(entity);
            db.SaveChanges();
        }

        public void InsertBulk(IEnumerable<T> list)
        {
            _entity.AddRange(list);
            db.SaveChanges();
        }

        public void Update(T entity)
        {
            _entity.Update(entity);
            db.SaveChanges();
        }
    }
}
